package org.example.auth.conf;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.example.system.common.utils.JwtUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Mybatis-Plus自动填充功能
 * @author joey
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        Object createBy = getFieldValByName("createBy", metaObject);
        Object updateBy = getFieldValByName("updateBy", metaObject);
        Object createTime = getFieldValByName("createTime", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);

        if (createBy == null) {
            this.setFieldValByName("createBy", JwtUtils.getCurrentUserIdNoException(), metaObject);
        }
        if (updateBy == null) {
            this.setFieldValByName("updateBy", JwtUtils.getCurrentUserIdNoException(), metaObject);
        }
        if (createTime == null) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if (updateTime == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        Object updateBy = getFieldValByName("updateBy", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (updateBy == null) {
            this.setFieldValByName("updateBy", JwtUtils.getCurrentUserIdNoException(), metaObject);
        }
        if (updateTime == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }
}
